import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

let loadTimeoutId;

axios.interceptors.request.use((conf) => {
  loadTimeoutId = setTimeout(() => {
    new Vue({}).$vux.loading.show({
      text: 'Loading'
    });
  }, 500);
  setTimeout(() => {
    new Vue({}).$vux.loading.hide();
  }, 600);
  conf.auth = {
    username: 'linqinghu',
    password: '123456'
  };
  return conf
}, (error) => {
  //new Vue({}).$message.error('请求失败');
  return Promise.reject(error)
});
axios.interceptors.response.use((res) => {
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  // console.log(res.data.code);
  if(res.data.code==250){
    console.log(122222222);
    window.location.href='http://192.168.31.28:8013/index.html';
    return false;
  }
  return res.data;
  // if (res.data.code === 0) {
  //   return res.data;
  //   // new Vue({}).$vux.toast.show({type: 'warn', text: '请求错误'});
  //   // new Vue({}).$vux.toast.show({type:'text', text:`${res.data.msg}`, width:`50%`, time:2500});
  // } else if (res.data.code === 1) {
  //   return res.data
  // } else if (res.data.code === 2) {
  //
  // } else if (res.data.code === 3) {
  //
  // } else if (res.data.code === 4) {
  //
  // } else if (res.status === 200) {
  //   return res.data;
  // } else {
  //
  // }
  // return Promise.reject(res);
}, (error) => {
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  new Vue({}).$vux.toast.show({type: 'warn', text: '响应失败'});
  return Promise.reject(error)
});

const ajax = {
  get: (url, params) => {
    return axiosRequestParams(url, 'get', params, 10000);
  },
  post: (url, params) => {
    return axiosRequestParams(url, 'post', params, 15000);
  },
  uploadForm: (url, params, formData) => {
    // 处理提交评论的个自定义方法
    return axiosRequestParams(url, 'post', params, 0, formData);
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, formData) {

  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};

  paramsOrData.token  = window.localStorage.getItem('ZM_token');

  if (method === 'get' || method === 'delete' || method === 'head') {
    params = paramsOrData;
    data = {};
  } else {
    params = {};
    data = qs.stringify(paramsOrData);
  }

  // 有formData 走这个；
  if (formData != null) {
    for (let attr in paramsOrData) {
      formData.append(attr, paramsOrData[attr]);
    }
  }
  return axiosRequest({
    method: method,
    url: url,
    params: params,
    data: formData ? formData : data,
    timeout: 10000
  })
}

function axiosRequest(conf) {
  return axios ({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  })
}

Vue.prototype.$ajax = ajax;

